package application;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * This class is for reading a text from a file and either return it line by line or all at once.
 */
public class TextReader {
	BufferedReader br;
	String line;
	int length;
	boolean isReady;

	public TextReader(String fileName) throws IOException {
		br = new BufferedReader(new FileReader(fileName));
		RandomAccessFile raf = new RandomAccessFile(new File(fileName), "r");
		length = (int) raf.length();
		raf.close();
	}

	/**
	 * Checks if there is another line.
	 */
	public boolean hasNextLine() {
		try {
			br.mark(length);
			line = br.readLine();
			br.reset();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return line != null;
	}

	/**
	 * Returns the next line.
	 */
	public String nextLine() {
		try {
			line = br.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return line;
	}

	/**
	 * Returns the text as how it is presented in the file.
	 * @throws IOException 
	 */
	public String readAll() throws IOException {
		StringBuilder sb = new StringBuilder();
		String newLine = System.getProperty("line.separator");
			for (String line = br.readLine(); line != null; line = br.readLine()) {
				br.mark(length);
				String nextLine = br.readLine();
				br.reset();
				if (nextLine == null) {
					sb.append(line);
				} else {
					sb.append(line).append(newLine);
				}
			}
		return sb.toString();
	}

	public void close() {
		try {
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
